<template>
  <div class="project_module_cascade">
    <el-cascader
      v-model="selectedList"
      ref="cascaderRef"
      :props="cascadeProps"
      clearable
      @change="changeSelect"
      class="cascader"
    />
  </div>
</template>

<script>
import {
  ref,
  reactive,
  watch,
  getCurrentInstance,
  onMounted,
  nextTick,
  computed,
} from "vue";
import { useStore } from "vuex";

export default {
  name: "ProjectModuleCascade",
  props: {
    // 用来回显的名称
    moduleNames: {
      type: String,
      default: "",
    },
  },
  setup(props, context) {
    // ------------------ 通用属性 start --------------------
    const { proxy } = getCurrentInstance();
    const $api = proxy.$api;
    const store = useStore();

    const userInfo = computed(() => store.state.user.userInfo);
    // ------------------ 通用属性 end ----------------------

    const cascaderRef = ref(null);
    const selectedList = ref([]);

    // 级联选择器
    const cascadeProps = reactive({
      label: "name",
      value: "id",
      lazy: true,
      checkStrictly: true, // 可单独选父级节点
      lazyLoad(node, resolve) {
        // console.log("node => ", node);
        const { level } = node;
        let parentId;
        if (level === 0) {
          parentId = null;
        } else {
          parentId = node.value;
        }
        $api.cascade
          .getCascadeList({
            parentId,
            orgId: userInfo.value.orgId,
          })
          .then((res) => {
            // console.log("getCascadeList => res", res);
            const nodes = res.data.map((item) => {
              return {
                ...item,
                leaf: item.childrenId === null,
              };
            });
            resolve(nodes);
          })
          .catch((err) => {
            console.error("getCascadeList error: ", err);
          });
      },
    });

    // 属性监听
    watch(
      () => props.moduleNames,
      (newVal) => {
        // 用于编辑时，动态加载的 cascade 回显
        nextTick(() => {
          if (newVal) {
            cascaderRef.value.inputValue = newVal.replaceAll("|", " / ");
          } else {
            cascaderRef.value.inputValue = "";
          }
        });
        // if (cascaderRef.value) {
        //   if (newVal) {
        //     cascaderRef.value.inputValue = newVal.replaceAll("|", " / ");
        //   } else {
        //     cascaderRef.value.inputValue = "";
        //   }
        // }
      }
    );

    const changeSelect = (val) => {
      // console.log("changeSelect => val", val);
      const choose = cascaderRef.value.getCheckedNodes();
      console.log("choose => ", choose);
      let moduleIds = "";
      let moduleNames = "";
      if (choose && choose.length) {
        moduleIds = choose[0].pathValues.join("|");
        moduleNames = choose[0].pathLabels.join("|");
      }
      // 触发事件，把数据传递给父组件
      context.emit("change", { moduleIds, moduleNames });
    };

    // 清空级联选中的数据
    const clear = () => {
      selectedList.value = [];
      // 清空 cascade 回显
      if (cascaderRef.value) {
        console.log("清空级联选中的数据");
        cascaderRef.value.panel.clearCheckedNodes();
        cascaderRef.value.inputValue = "";
      }
    };

    // 组件钩子
    onMounted(() => {});

    return {
      cascaderRef,
      selectedList,
      changeSelect,
      cascadeProps,
      clear,
    };
  },
};
</script>

<style lang="less" scoped>
.project_module_cascade {
  :deep(.cascader) {
    width: 100%;
  }
}
</style>
